'''
    @project: Masdevallia
    @author: Austin Baker
    @created: 2/22/2014
    @license: http://opensource.org/licenses/mit-license.php

    The MIT License (MIT)

    Copyright (c) 2014 Austin Baker
    
    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:
    
    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.
    
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
    
    ------
    
    About:
        Information tile widget. Used in the Rig Tools window.
    
    Making Icons:
        1) Icons for Info Tiles should be 60x40px.
        2) Add new images to the Gimp file info_tile.xcf.
            a) Export the image as a PNG.
        3) Add the image to the qt_icons.qrc file.
        4) Run the batch file build_qt_qrc.bat.
            a) This will update qt_icons_resources.py
        5) Loading of the correct asset from the resources file is handled
            automatically by the code below.        
'''

'''
============================================================
--->>   IMPORT MODULES
============================================================
'''
import sys, types, os

import maya.OpenMaya as OpenMaya

import masdevallia.settings.PathConstants as PathConstants
import masdevallia.utility.WindowUtility as WinUtility
import masdevallia.modeling.Curves as Curves
import masdevallia.utility.XML as XML
import masdevallia.utility.Dag as Dag
import masdevallia.utility.Matrix as Matrix

from PySide import QtCore
from PySide import QtGui
import masdevallia.windows.icons.qt_icons_resources

'''
============================================================
--->>   GLOBAL VARIABLES
============================================================
'''
form_class, base_class = WinUtility.loadUiType( PathConstants.WIDGET_INFO_TILE_GUI )

'''
============================================================
--->>   INFO TILE CLASS
============================================================
'''

# Create CSS settings for each type of tile.
CONTROLS_CURVE = '''
        QFrame {
            background-color: rgb(110,90,90);
            border: 1px solid rgb(96,78,78);
            border-radius: 4px;
        }
        QLabel {
            background-color: transparent;
            border: 10px;
            border-radius:10px;
        }'''
        
CONTROLS_SURFACE = '''
        QFrame {
            background-color: rgb(90,110,90);
            border: 1px solid rgb(77,94,77);
            border-radius: 4px;
        }
        QLabel {
            background-color: transparent;
            border: 0px;
        }'''
        
CONTROLS_POLYGON = '''
        QFrame {
            background-color: rgb(90,90,110);
            border: 1px solid rgb(80,80,97);
            border-radius: 4px;
        }
        QLabel {
            background-color: transparent;
            border: 0px;
        }'''
CONTROLS = {'curve':CONTROLS_CURVE,
            'surface':CONTROLS_SURFACE,
            'polygon':CONTROLS_POLYGON}


SPACERS_BASIC = '''
        QFrame {
            background-color: rgb(110,110,70);
            border: 1px solid rgb(93,93,59);
            border-radius: 4px;
        }
        QLabel {
            background-color: transparent;
            border: 0px;
        }'''
SPACERS = {'basic':SPACERS_BASIC}


JOINTS_BASIC = '''
        QFrame {
            background-color: rgb(90,110,110);
            border: 1px solid rgb(78,96,96);
            border-radius: 4px;
        }
        QLabel {
            background-color: transparent;
            border: 0px;
        }'''
JOINTS = {'basic':JOINTS_BASIC}


ROOTS_BASIC = '''
        QFrame {
            background-color: rgb(110,90,110);
            border: 1px solid rgb(97,79,97);
            border-radius: 4px;
        }
        QLabel {
            background-color: transparent;
            border: 0px;
        }'''
ROOTS = {'basic':ROOTS_BASIC}


CSS_OPTIONS = {'controls':CONTROLS,
               'joints':JOINTS,
               'roots':ROOTS,
               'spacers':SPACERS}

 
class InfoTile( form_class, base_class ):
    def __init__( self, nameLabel=None, typeLabel=None, subtypeLabel=None, filePath=None ):
        super( InfoTile, self).__init__()
        self.setupUi( self )
        self.setObjectName( nameLabel )
        
        self.NameLabel.setText( nameLabel )
        self.SubtypeLabel.setText( subtypeLabel )
        
        self.name = nameLabel
        self.type = typeLabel
        self.subtype = subtypeLabel
        self.filePath = filePath
        self.iconPath = None 
        
        self.initUI()
        
    def initUI( self ):
        mainDictionary = CSS_OPTIONS[ self.type ]
        self.Frame.setStyleSheet( mainDictionary[ self.subtype ] )
        self.getIcon()
        
    def getIcon( self ):
        if os.path.exists( self.filePath ):
            xml_data = XML.XML().readFile( inFilename=self.filePath )
            
            if xml_data is not None:
                for xml_object in xml_data.objects:
                    if xml_object.icon is not None:
                        sheet = '''background-image: url(:/{0}/{1}.png);
                                background-repeat: no-repeat;
                                border: 1px solid rgb(96,78,78);
                                border-radius: 4px;'''.format( self.subtype, xml_object.icon )                            
                        self.PixFrame.setStyleSheet( sheet )
                        
                        '''
                        palette = QtGui.QPalette()
                        pixmap = QtGui.QPixmap( self.iconPath )
                        brush = QtGui.QBrush( pixmap )
                        
                        palette.setBrush( QtGui.QPalette.Background, brush )
                        self.PixFrame.setPalette( palette )
                        '''
                        break
    
    def mouseDoubleClickEvent( self, event ):
        '''
        Double-click event triggers the creation of the asset associated
        with the tile.
        '''
        xml_data = XML.XML().readFile( inFilename=self.filePath )
        if xml_data is not None:
            prevSel = OpenMaya.MSelectionList()
            OpenMaya.MGlobal.getActiveSelectionList( prevSel )            
            
            final_obj = None
            for object_entry in xml_data.objects:
                object_name = object_entry.name
                object_type = object_entry.type
                
                if object_type == 'Curve':
                    curves = []
                    for element in object_entry.elements:
                        elem_name = element.name
                        elem_type = element.type
                        elem_degree = element.degree
                        elem_form = element.form
                        curve_data = Curves.getCurveDataFromXMLElement( element )
                        curve = Curves.createCurve( object_name, elem_name, inCurveData=curve_data, inDegree=elem_degree, inForm=elem_form )
                        curves.append( curve )
                    
                    if len( curves ) > 1:
                        curve_node = Curves.createCompoundCurve( inCurves=curves )
                        final_obj = curve_node.name
                    else:
                        final_obj = curves[0]
                        
            # If there is an object selected then match the new object's
            # transforms to the selected object.
            if prevSel.length() >= 1:
                # Get the first item in the list of the previously selected
                # items. When then get it's matrix information.
                prev_dag = OpenMaya.MDagPath()
                component = OpenMaya.MObject()
                prevSel.getDagPath( 0, prev_dag, component )
                source_matrix = Matrix.Matrix( str(prev_dag.fullPathName()), 'worldMatrix' )
                
                # Get the matrix information for the new object.
                target_matrix = Matrix.Matrix( final_obj, 'worldMatrix' )
                
                # Match the new object to the source object.
                target_matrix.setTranslation( source_matrix.getTranslation() )
                target_matrix.setRotation( source_matrix.getRotation( OpenMaya.MQuaternion ) )
                
                
    def str_to_class( self, field ):
        '''
        Converts a string to a class.
        
        @param field: String. Name of a class.
        @return: Instance of class.
        '''
        try:
            identifier = getattr(sys.modules[__name__], field)
            
        except AttributeError:
            raise NameError("%s doesn't exist." % field)
        
        if isinstance(identifier, (types.ClassType, types.TypeType)):
            return identifier
        
        raise TypeError("%s is not a class." % field)